package com.lgp;

import javax.websocket.Session;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class SessionUtils {

	public static Map<String, Session> clients = new ConcurrentHashMap<>();

	public static void put(String relationId, Session session){
		clients.put(getKey(relationId), session);
	}

	public static Session get(String relationId){
		return clients.get(getKey(relationId));
	}

	public static void remove(String relationId){
		clients.remove(getKey(relationId));
	}

	/**
	 * 判断是否有连接
	 * @param relationId
	 * @return
	 */
	public static boolean hasConnection(String relationId) {
		return clients.containsKey(getKey(relationId));
	}

	/**
	 * 组装唯一识别的key
	 * @param relationId
	 * @return
	 */
	public static String getKey(String relationId) {
		return relationId;
	}

	/**
	 * 给所有客户端发送消息
	 * @param message
	 */
	public static void sendMessage(String message){
		for(Map.Entry<String,Session> e: clients.entrySet() ){
			e.getValue().getAsyncRemote().sendText(message);
		}
	}
}
